package com.txc.cloud.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.txc.cloud.admin.entity.UserRoleEntity;
import com.txc.cloud.admin.mapper.UserRoleMapper;
import com.txc.cloud.admin.service.IUserRoleService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户-角色表 服务实现类
 * </p>
 *
 * @author TXC
 * @since 2023-08-02
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleEntity> implements IUserRoleService {

    @Override
    public void flush(Long userId, List<Long> roleIds) {
        List<UserRoleEntity> userRoleList =
                baseMapper.selectList(Wrappers.<UserRoleEntity>lambdaQuery().eq(UserRoleEntity::getUserId, userId));
        Map<Long, UserRoleEntity> userRoleMap =
                userRoleList.stream().collect(Collectors.toMap(UserRoleEntity::getRoleId, e -> e));
        roleIds.forEach(roleId -> {
            UserRoleEntity roleDept = userRoleMap.get(roleId);
            if (ObjectUtil.isNotNull(roleDept)) {
                userRoleMap.remove(roleId);
            } else {
                UserRoleEntity userRoleEntity = new UserRoleEntity();
                userRoleEntity.setRoleId(roleId);
                userRoleEntity.setUserId(userId);
                userRoleEntity.insert();
            }
        });
        userRoleMap.forEach((k, v) -> v.deleteById());
    }
}
